package com.zsh.wanandroid.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dxq.basic_ui_library.loadSirCallBack.EmptyCallback;
import com.dxq.basic_ui_library.loadSirCallBack.ErrorCallback;
import com.dxq.basic_ui_library.loadSirCallBack.LoadingCallback;
import com.dxq.basic_ui_library.manager.RecyclerViewLinearLayoutManager;
import com.zsh.wanandroid.R;
import com.zsh.wanandroid.api.ApiService;
import com.zsh.wanandroid.base.BaseActivity;
import com.zsh.wanandroid.base.BaseFragment;
import com.zsh.wanandroid.bean.ArticleTags;
import com.zsh.wanandroid.bean.BaseResult;
import com.zsh.wanandroid.bean.PageResult;
import com.zsh.wanandroid.bean.ArticleBean;
import com.zsh.wanandroid.http.ApiRequest;
import com.zsh.wanandroid.ui.activity.ArticleActivity;
import com.zsh.wanandroid.ui.adapter.SquareAdapter;

import java.io.Serializable;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author zsh
 * @date 2020/3/12.
 * 功能：广场fragment
 */

public class SquareFragment extends BaseFragment {

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;

    //private FragmentCommonAdapter mAdapter;
    private SquareAdapter squareAdapter;

    private final static int DEFAULT_PAGE = 0;
    private int currentPage = DEFAULT_PAGE;
    private int pageCount;

    //创建SquareFragment
    public static SquareFragment newInstance(Bundle bundle) {
        SquareFragment fragment = new SquareFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (null != arguments) {

        }
    }

    @Override
    protected int onCreateFragmentView() {
        return R.layout.fragment_common;
    }

    @Override
    protected void initView(View view) {
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        //添加Android自带的分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        recyclerView.setLayoutManager(new RecyclerViewLinearLayoutManager(getContext()));
        initAdapter();
        initSwipeRefreshLayout();
    }

    private void initAdapter() {
        squareAdapter = new SquareAdapter(R.layout.content_item);
        recyclerView.setAdapter(squareAdapter);

        //item点击事件
        squareAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<ArticleBean<ArticleTags>> data = adapter.getData();
                Bundle bundle = new Bundle();
                bundle.putSerializable("data", (Serializable) data.get(position));
                BaseActivity activity = (BaseActivity) getActivity();
                activity.startActivity(ArticleActivity.class, bundle);
            }
        });
    }
    private void initSwipeRefreshLayout() {
        //下拉刷新
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = DEFAULT_PAGE;
                loadNet();
            }
        });

        //上拉加载更多
        squareAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadNet();
            }
        });
    }


    /**
     * 获取广场接口数据
     */
    @Override
    protected void loadNet() {
        ApiService apiService = ApiRequest.getInstance(getContext()).create(ApiService.class);
        apiService.getSquareList(currentPage).enqueue(new Callback<BaseResult<PageResult<ArticleBean<ArticleTags>>>>() {
            @Override
            public void onResponse(Call<BaseResult<PageResult<ArticleBean<ArticleTags>>>> call,
                                   Response<BaseResult<PageResult<ArticleBean<ArticleTags>>>> response) {
                swipeRefreshLayout.setRefreshing(false);
                BaseResult<PageResult<ArticleBean<ArticleTags>>> body = response.body();
                if (null == body) {
                    mBaseLoadService.showCallback(EmptyCallback.class);
                    return;
                }
                PageResult<ArticleBean<ArticleTags>> data = body.getData();
                currentPage = data.getCurPage();
                pageCount = data.getPageCount();
                if (null == data) {
                    mBaseLoadService.showCallback(EmptyCallback.class);
                    return;
                }
                List<ArticleBean<ArticleTags>> datas = data.getDatas();
                if (null != datas && datas.size() > 0) {
                    mBaseLoadService.showSuccess();
                    if (currentPage == DEFAULT_PAGE+1) {
                        //下拉刷新
                        squareAdapter.replaceData(datas);
                    } else {
                        //上拉加载更多
                        squareAdapter.addData(datas);
                    }
                    if (currentPage < pageCount) {
                        squareAdapter.loadMoreComplete();//加载完成（注意不是加载结束，而是本次数据加载结束并且还有下页数据）
                    } else {
                        squareAdapter.loadMoreEnd();//加载结束
                    }
                } else {
                    mBaseLoadService.showCallback(EmptyCallback.class);
                }
            }

            @Override
            public void onFailure(Call<BaseResult<PageResult<ArticleBean<ArticleTags>>>> call, Throwable t) {
                swipeRefreshLayout.setRefreshing(false);
                mBaseLoadService.showCallback(ErrorCallback.class);
                currentPage = 0;
            }
        });
    }

    @Override
    protected void onNetReload(View v) {
        mBaseLoadService.showCallback(LoadingCallback.class);
        loadNet();
    }
}
